<template>
  <s-layout>
    <view class="container">
       <!-- Header Section (similar to target) -->
       <view class="header-box">
        <text
          class="cicon-key"
          style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
        ></text>
        <text class="title">更改个人信息</text> <!-- Changed title -->
      </view>

      <!-- Avatar Section -->
      <view class="form-card avatar-section" @tap="chooseAvatar">
        <text class="label">头像</text>
        <view class="avatar-right">
          <image class="avatar-img" :src="displayAvatarUrl" mode="aspectFill" />
          <image class="arrow-icon" src="@/static/tabs/更多.png" mode="scaleToFill" />
        </view>
      </view>

      <!-- Basic Information Section -->
      <!-- <view class="form-card info-section"> -->

        <!-- <fui-input
          label="姓名"
          placeholder="请输入姓名"
          v-model="formData.name"
          :inputBorder="false"
          :borderBottom="true"
          borderColor="#EEEEEE"
        >
        </fui-input> -->

        <!-- Account (Display Only) -->
        <!-- <fui-input
          label="账号"
          placeholder="用户账号"
          :value="userInfo?.wx_user || 'N/A'"
          :inputBorder="false"
          :borderBottom="true"
          borderColor="#EEEEEE"
          disabled
          :disabledStyle="{ color: '#888' }"
        >
        </fui-input> -->

        <!-- Phone -->
        <!-- <fui-input
          label="电话"
          placeholder="请输入手机号码"
          v-model="formData.phone"
          inputType="number"
          maxlength="11"
          :inputBorder="false"
          :borderBottom="false"
        >
        </fui-input> -->

      <!-- </view> -->

      <!-- Submit Button -->
      <view class="submit-btn-container">
        <view class="submit-btn" @click="saveChanges">
          <text class="btn-text">确认修改</text>
        </view>
      </view>

    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import other from "@/sheep/api/other";
// Removed unused dayjs import

// --- State ---
const formData = reactive({
  name: "",
  phone: "",
});

// Holds the URL to display (can be existing URL or temporary local path)
const displayAvatarUrl = ref('');
// Holds the *new* avatar path returned from the server after upload
const newAvatarServerPath = ref<string | null>(null);

// Get current user info from store or API
const userInfo = sheep.$store("user").userInfo; // Assuming store has user info like { ur_name, wx_user, ur_phone, wx_avatarUrl }

// --- Lifecycle Hooks ---
onLoad(async () => {
  uni.showLoading({ title: '加载中...' });
  try {
      // Assuming userInfo is populated in the store after login
      if (userInfo) {
          // Map relevant fields to formData
          formData.name = userInfo.ur_name || '';       // Adjust 'ur_name' if needed
          formData.phone = userInfo.ur_phone || '';     // Adjust 'ur_phone' if needed

          // Set initial display avatar
          displayAvatarUrl.value = userInfo.wx_avatarUrl ; // Default avatar

          // Username (wx_user) is displayed directly in the template from userInfo

      } else {
          console.error("User info not found in store.");
          uni.showToast({ title: '请先登录', icon: 'none' });
          // Potentially redirect
      }

      // --- Alternative: Fetch data from API (Keep if needed) ---
      // const response = await sheep.$api.user.profile();
      // ... (keep fetch logic if you might use it)

  } catch (error) {
      console.error("Error loading user data:", error);
      uni.showToast({ title: '加载数据出错', icon: 'none' });
  } finally {
      uni.hideLoading();
  }
});


// --- Methods ---

// Choose and Upload Avatar
const chooseAvatar = async () => {
  try {
    const chooseRes = await uni.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
    });

    const tempFilePath = chooseRes.tempFilePaths[0];
    // Update preview immediately with local file
    displayAvatarUrl.value = tempFilePath;
    newAvatarServerPath.value = null; // Reset server path until upload succeeds

    uni.showLoading({ title: "上传头像中..." });

    // --- New Upload Logic using uni.uploadFile ---
    const upLoadrUrl = "https://assess.yuejin-tech.com/app_api.php?t=upload&op=image_upload&role=third_party&type=avatarUrl"

    // Add authentication token if required by your API
    const token = sheep.$store('user').getToken ? sheep.$store('user').getToken() : null; // Check if getToken exists
    const headers: Record<string, any> = {};
    if (token) {
        // Adjust header based on your API's requirement (e.g., 'Authorization', 'token', 'x-token')
        headers['Authorization'] = 'Bearer ' + token;
        // Or headers['token'] = token;
    }

    uni.uploadFile({
        url: upLoadrUrl,
        filePath: tempFilePath,
        name: 'file', // Ensure 'file' is the expected field name for the image data on your server
        header: headers,
        // formData: { // Add any other form data parameters your API requires for upload
        //     'some_field': 'some_value'
        // },
        success: (uploadFileRes) => {
            console.log("Upload success raw response:", uploadFileRes);
            try {
                // Attempt to parse the server response data, removing potential BOM
                const res = JSON.parse(uploadFileRes.data.replace(/\ufeff/g, "") || "{}");
                console.log("Parsed server response:", res);

                // IMPORTANT: Check the structure of 'res' from your API
                // Assuming the API returns a structure like { code: 200, data: '/path/to/image.jpg', msg: '...' }
                // Adjust the condition below based on your actual successful response structure
                if (res.data) { // Simple check: if 'data' exists and is a string (path)
                    const relativePath = res.data;
                    const serverUrl = relativePath; // Construct the full URL

                    console.log("上传成功，服务器URL:", serverUrl);
                    newAvatarServerPath.value = serverUrl; // Store the final URL from the server
                    displayAvatarUrl.value = serverUrl
                    // Optional: Update preview to server URL if desired, otherwise local preview is already shown
                    // displayAvatarUrl.value = serverUrl;

                    uni.hideLoading();
                    uni.showToast({ title: "头像上传成功", icon: "success", duration: 1500 });

                } else {
                    // Handle cases where upload succeeded (HTTP 200) but the API indicates an error in the JSON response
                    const errorMessage = res.msg || res.message || "头像上传失败"; // Get error message from response if available
                    console.error("头像上传失败 (API Error):", errorMessage, res);
                    uni.hideLoading();
                    uni.showToast({ title: errorMessage, icon: "none" });
                    // Revert preview to original avatar
                    displayAvatarUrl.value = userInfo?.wx_avatarUrl 
                    newAvatarServerPath.value = null;
                }
            } catch (parseError) {
                console.error("解析服务器响应失败:", parseError);
                console.error("Raw server data:", uploadFileRes.data);
                uni.hideLoading();
                uni.showToast({ title: "处理服务器响应失败", icon: "none" });
                // Revert preview
                displayAvatarUrl.value = userInfo?.wx_avatarUrl 
            }
        },
        fail: (err) => {
            console.error("头像上传失败 (uni.uploadFile):", err);
            uni.hideLoading();
            uni.showToast({ title: "头像上传网络错误", icon: "none" });
            // Revert preview
            displayAvatarUrl.value = userInfo?.wx_avatarUrl 
            newAvatarServerPath.value = null;
        },
        // complete: () => {
        //     // Optional: Code that runs after success or fail
        // }
    });
    // --- End of New Upload Logic ---

  } catch (chooseError: any) {
    // Handle cancellation or error during image selection
    if (chooseError.errMsg && chooseError.errMsg.includes('cancel')) {
      console.log('用户取消选择头像');
      // No toast needed for cancellation
    } else {
      console.error("选择头像时发生错误:", chooseError);
      uni.showToast({ title: "选择图片失败", icon: "none" });
    }
    // Ensure loading is hidden if chooseImage fails before upload starts
    uni.hideLoading();
  }
};


// Validate Phone (Simple Example)
const isValidPhone = (phone: string): boolean => {
    const phoneRegex = /^\d{11}$/;
    return phoneRegex.test(phone);
}

// Save Changes
const saveChanges = async () => {
  // Validation

  uni.showLoading({ title: "正在保存...", mask: true });
console.log(displayAvatarUrl.value,"displayAvatarUrl.value");

  // Construct the payload
  const payload: Record<string, any> = {
    wx_avatarUrl: newAvatarServerPath.value.replace(/^https?:\/\/[^\/]+/, ""),
    wx_id: sheep.$store("user").userInfo.wx_id,
  };

  // Include avatar URL *only if* a new one was successfully uploaded and stored
  if (newAvatarServerPath.value) {
    // IMPORTANT: Ensure the key 'avatar' matches your backend API's expected field name for the avatar URL
    payload.avatar = newAvatarServerPath.value;
  }

  try {
    // Replace with your actual update profile API endpoint
    const response = await other.userEdit(payload); // Example: assumes API accepts { name, phone, avatar? }

    uni.hideLoading();

    if (response.code === 200) {
      uni.showToast({
        title: "修改成功",
        icon: "success",
        duration: 1500,
      });

      // Update user info in the store for immediate reflection elsewhere
      const updatedUserInfo = { ...sheep.$store("user").userInfo };
      updatedUserInfo.ur_name = formData.name;   // Adjust store field name if needed
      updatedUserInfo.ur_phone = formData.phone; // Adjust store field name if needed
      updatedUserInfo.wx_avatarUrl = displayAvatarUrl.value;
      // Ensure the updateUserInfo action/mutation exists and works correctly in your user store
      if (sheep.$store("user").updateUserInfo) {
           sheep.$store("user").updateUserInfo(updatedUserInfo);
      } else {
          console.warn("Store action 'updateUserInfo' not found. Local store state might be stale.");
          // Fallback: Manually update the reactive userInfo if updateUserInfo action is missing
          Object.assign(sheep.$store("user").userInfo, updatedUserInfo);
      }


      // Optionally navigate back after a delay
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);

    } else {
      uni.showToast({
        title: response.msg || "保存失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("Save changes error:", error);
    uni.showToast({
      title: "网络错误或服务异常",
      icon: "none",
      duration: 2000,
    });
  }
};

</script>

<style lang="scss" scoped>
// Styles remain the same as provided in the original code
.container {
  padding: 20rpx 30rpx 120rpx 30rpx; /* Add bottom padding for fixed button */
  background: #f8f9fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 0 20rpx; /* Padding for content inside card */
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.05);
}

.avatar-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 140rpx;
  padding: 20rpx; /* Use card padding */
  .label {
    font-size: 33rpx;
    color: #333;
    font-weight: 500;
  }
  .avatar-right {
    display: flex;
    align-items: center;
  }
  .avatar-img {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    border: 1px solid #eee;
    margin-right: 15rpx;
  }
  .arrow-icon {
    width: 25rpx;
    height: 25rpx;
    opacity: 0.6;
  }
}
/* Header styles */
.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}
.info-section {
  padding: 20rpx 20rpx 0 20rpx; /* Top/Horizontal padding */
    ::v-deep .fui-section {
      margin-left: -20rpx !important; // Adjust section position
      margin-right: -20rpx !important;
    }
     /* Ensure fui-input borders are handled correctly */
    ::v-deep .fui-input__wrap {
      padding-left: 0 !important;
      padding-right: 0 !important;
    }
    ::v-deep .fui-input__padding {
       padding: 26rpx 0 !important; // Consistent padding
    }
}


// Submit Button Styling (Fixed at bottom)
.submit-btn-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx calc(20rpx + env(safe-area-inset-bottom)); // Padding and safe area
    background-color: #f8f9fa; // Match page background or use #fff if preferred
    z-index: 10;
}

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 82, 217, 0.3);
  transition: background 0.3s ease;

  &:active {
    background: linear-gradient(135deg, darken(#0052d9, 5%), darken(#2979ff, 5%));
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
  }
}
</style>
